import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/auth_portal_dialog.dart';
import 'package:raze/artifacts/circle_join_dialog.dart';
import 'package:raze/artifacts/notifier_glimmer.dart';
import 'package:raze/lore/chronicle/circle_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 圈子列表页面
class GroupListRealms extends StatelessWidget {
  const GroupListRealms({super.key});

  @override
  Widget build(BuildContext context) {
    final circleChronicle = Get.find<CircleChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              _constructTitleBar(),

              // 圈子列表
              Expanded(
                child: Obx(() {
                  final circles = circleChronicle.circleList;
                  if (circles.isEmpty) {
                    return Center(
                      child:
                          Text('No circles available')
                              .applyTypeSize(16.sp)
                              .applyTypeColor(RazeConstants.black)
                              .applyNotoSans(),
                    );
                  }

                  return ListView.builder(
                    padding: EdgeInsets.symmetric(
                      horizontal: 16.w,
                      vertical: 16.h,
                    ),
                    itemCount: circles.length,
                    itemBuilder: (context, index) {
                      final circle = circles[index];
                      return _renderCircleCard(
                        circle,
                        circleChronicle,
                        userChronicle,
                      );
                    },
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建标题栏
  Widget _constructTitleBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: RazeConstants.background,
                  borderRadius: BorderRadius.circular(8.r),
                  border: Border.all(color: RazeConstants.black, width: 1.5.w),
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  size: 24.sp,
                  color: RazeConstants.black,
                ),
              )
              .withRightBottomShadow(thickness: 1)
              .withTouchResonance(onTap: () => Get.back()),

          Expanded(
            child: Center(
              child: Text('Group')
                  .applyTypeSize(20.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyBagelFatOne(weight: FontWeight.w400),
            ),
          ),

          // 占位（保持返回按钮居中）
          30.w.boxWidth,
        ],
      ),
    );
  }

  /// 渲染圈子卡片
  Widget _renderCircleCard(
    dynamic circle,
    CircleChronicle circleChronicle,
    UserChronicle userChronicle,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 26.h),
      child: AspectRatio(
        aspectRatio: 343 / 93, // 宽高比 343/93
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/circle-card.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              // 左侧：圈子名称和按钮
              Container(
                width: double.infinity,
                padding: EdgeInsets.only(left: 16.w, right: 120.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 圈子名称
                    _buildCircleTitleWithBorder(circle.title),
                    6.h.boxHeight,

                    // 按钮（根据登录状态和加入状态显示）
                    Obx(() {
                      final currentUser = userChronicle.currentUser;
                      if (currentUser == null) {
                        // 未登录：显示 Join In 按钮
                        return _buildJoinButton();
                      }

                      // 已登录：检查是否加入
                      final isMember = circleChronicle.checkIsMember(
                        circle.id,
                        currentUser.id,
                      );

                      if (isMember) {
                        // 已加入：显示 Chat 按钮
                        return _buildChatButton();
                      } else {
                        // 未加入：显示 Join In 按钮
                        return _buildJoinButton();
                      }
                    }),
                    12.h.boxHeight,
                  ],
                ),
              ),

              // 圈子图片
              Positioned(
                right: 25.w,
                bottom: 18.w,
                child: Center(
                  child: Container(
                    width: 87.w,
                    height: 87.w,
                    decoration: BoxDecoration(),
                    child: ClipRRect(
                      child: Image.asset(circle.image, fit: BoxFit.contain),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ).withTouchResonance(
        onTap:
            () => _handleCircleCardTap(circle, circleChronicle, userChronicle),
      ),
    );
  }

  /// 构建带边框效果的圈子标题
  Widget _buildCircleTitleWithBorder(String title) {
    return Text(title)
        .applyTypeSize(20.sp)
        .applyTypeColor(RazeConstants.white)
        .applyBagelFatOne(
          weight: FontWeight.w400,
          shadows: [
            Shadow(
              offset: Offset(-1.w, -1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(1.w, -1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(-1.w, 1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(1.w, 1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(0, -1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(0, 1.w),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(-1.w, 0),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
            Shadow(
              offset: Offset(1.w, 0),
              blurRadius: 0,
              color: RazeConstants.black,
            ),
          ],
        );
  }

  /// 构建加入按钮（带底层盒子）
  Widget _buildJoinButton() {
    return SizedBox(
      width: 70.w,
      height: 25.h,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 底层盒子（右下角偏移）
          Positioned(
            top: 4.w,
            left: 4.w,
            right: -4.w,
            bottom: -4.w,
            child: Container(
              decoration: BoxDecoration(
                color: const Color(0xFFCACACA),
                borderRadius: BorderRadius.circular(4.r),
                border: Border.all(color: RazeConstants.black, width: 1.w),
              ),
            ),
          ),

          // 加入按钮
          Container(
            width: 70.w,
            height: 25.h,
            decoration: BoxDecoration(
              color: RazeConstants.white,
              borderRadius: BorderRadius.circular(4.r),
              border: Border.all(color: RazeConstants.black, width: 1.w),
            ),
            alignment: Alignment.center,
            child: Text('Join In')
                .applyTypeSize(14.sp)
                .applyTypeColor(RazeConstants.black)
                .applyNotoSans(weight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  /// 构建聊天按钮（带底层盒子）
  Widget _buildChatButton() {
    return SizedBox(
      width: 70.w,
      height: 25.h,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 底层盒子（右下角偏移）
          Positioned(
            top: 4.w,
            left: 4.w,
            right: -4.w,
            bottom: -4.w,
            child: Container(
              decoration: BoxDecoration(
                color: RazeConstants.darkYellow,
                borderRadius: BorderRadius.circular(4.r),
                border: Border.all(color: RazeConstants.black, width: 1.w),
              ),
            ),
          ),

          // 聊天按钮
          Container(
            width: 70.w,
            height: 25.h,
            decoration: BoxDecoration(
              color: RazeConstants.yellow,
              borderRadius: BorderRadius.circular(4.r),
              border: Border.all(color: RazeConstants.black, width: 1.w),
            ),
            alignment: Alignment.center,
            child: Text('Chat')
                .applyTypeSize(14.sp)
                .applyTypeColor(RazeConstants.black)
                .applyNotoSans(weight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  /// 处理圈子卡片点击
  void _handleCircleCardTap(
    dynamic circle,
    CircleChronicle circleChronicle,
    UserChronicle userChronicle,
  ) {
    final currentUser = userChronicle.currentUser;

    // 检查登录状态
    if (currentUser == null) {
      AuthPortalDialog.revealAuthPortal();
      return;
    }

    // 检查是否已加入
    final isMember = circleChronicle.checkIsMember(circle.id, currentUser.id);

    if (isMember) {
      // 已加入：跳转到圈子聊天页面
      Get.toNamed('/group-chat', parameters: {'circleId': circle.id});
    } else {
      // 未加入：弹出确认弹窗
      CircleJoinDialog.revealJoinDialog(
        circle: circle,
        onJoinConfirmed: () {
          // 提示
          NotifierGlimmer.revealSuccess('Joined circle successfully');
          // 加入圈子
          circleChronicle.joinCircle(circle.id, currentUser.id);
        },
      );
    }
  }
}
